var fs = require('fs');
var dataPath = './public/code/db.json';


/**
 *
 *
 * @param {*} callback
 */
exports.init = function(callback){
  fs.readFile(dataPath,'utf8',function(err,data){
    console.log(err,data)
    if(err){
      return callback(err);
    }
    callback(null,JSON.parse(data).students);
  })
}

/**
 *
 *
 * @param {*} body
 * @param {*} callback
 */
exports.add = function(body,callback){
  fs.readFile(dataPath,'utf8',function(err,data){
    if(err){
      return callback(err);
    }
    var students = JSON.parse(data).students;
    var obj = body;
    obj.id = (students.length-1 != -1)?(parseInt(students[students.length-1].id) + parseInt(1)):1;
    students.push(obj);
    var a = JSON.stringify({
      students
    })
    fs.writeFile(dataPath,a,function(err){
      if(err){
        callback(err);
      }
    })
    callback(null)
  })
}

/**
 *
 *
 * @param {*} e
 * @param {*} callback
 */
exports.initnew = function(id,callback){
  fs.readFile(dataPath,'utf8',function(err,data){
    if(err){
      return callback(err);
    }
    var students = JSON.parse(data).students;
    var obj = students.find(e=>e.id == id)
    callback(null,obj);
  })
}

/**
 *
 *
 * @param {*} e
 * @param {*} callback
 */
exports.updata = function(body,callback){
  fs.readFile(dataPath,'utf8',function(err,data){
    if(err){
      return callback(err)
    }
    var arr = JSON.parse(data).students;
    var idx = arr.findIndex(e=>e.id == body.id)
    arr[idx] = body;
    var students = {students:arr}
    fs.writeFile(dataPath,JSON.stringify(students),function(err){
      if(err){
        return callback(err);
      }
      callback(null)
    })
  })
}

/**
 *
 *
 * @param {*} id
 * @param {*} callback
 */
exports.delete = function(id,callback){
  fs.readFile(dataPath,'utf8',function(err,data){
    if(err){
      return callback(err);
    }
    var arr = JSON.parse(data).students;
    var idx = arr.findIndex(e=>e.id==id);
    arr.splice(idx,1);
    var students = {students:arr}
    fs.writeFile(dataPath,JSON.stringify(students),function(err){
      if(err){
        return callback(err);
      }
      callback(null);
    })
  })
}

/**
 *
 *
 * @param {*} keyWord
 * @param {*} callback
 */
exports.seach = function(keyWord,callback){
  fs.readFile(dataPath,function(err,data){
    if(err){
      return callback(err);
    }
    var arr = JSON.parse(data).students;
    var e = arr.filter(s=> s.name.indexOf(keyWord)>=0)
    callback(null,e)
  })
}